import { Provide, Scope, ScopeEnum, Config } from '@midwayjs/decorator';
import { OtaTaskService } from './firmware/ota_task.service';
import * as mqtt from 'mqtt';
import { Inject } from '@midwayjs/core';
import { WristbandAdvService } from './firmware/wristband_adv.service';
// import * as msgpack from 'msgpack-lite';
import { ActionLogOtaService } from './firmware/actionLogOta.service';
import { GatewayService } from './firmware/gateway.service';
// import { StudentWristbandService } from './firmware/student_wristband.service';
import { StudentService } from './firmware/student.service';
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class MqttService {
  @Config('mqtt')
  mqttConfig;

  @Inject()
  otaTaskService: OtaTaskService;
  @Inject()
  gatewayService: GatewayService;
  @Inject()
  studentService: StudentService;

  @Inject()
  otaActionLogService: ActionLogOtaService;
  @Inject()
  wristbandAdvService: WristbandAdvService;
  // 指定网关
  TOPIC_GW = 'gw/action';


  private client: mqtt.MqttClient;
  private clientShanghai: mqtt.MqttClient;

  // 上报数据给苏州
  async clientSuZhouToPublish(mac, otaTask) {
    console.log('上报数据给苏州', '网关地址', mac, otaTask)
    let TOPIC_GW;
    if (mac) {
      TOPIC_GW = `${this.TOPIC_GW}/${mac}`
    } else {
      TOPIC_GW = this.TOPIC_GW
    }
    this.client = mqtt.connect(this.mqttConfig.suzhou.host, {
      username: this.mqttConfig.suzhou.username,
      password: this.mqttConfig.suzhou.password,
      clientId: this.mqttConfig.suzhou.clientId,
      keepalive: this.mqttConfig.suzhou.keepalive,
      reconnectPeriod: this.mqttConfig.suzhou.reconnectPeriod,
    });

    if (otaTask) {
      this.publish(TOPIC_GW, otaTask)
    }
    this.client.on('error', (err) => console.error('MQTT connection error:', err));
    this.client.on('close', () => console.log('MQTT connection closed'));
    this.client.on('offline', () => console.warn('MQTT client is offline'));
  }

  // 上报xbm 名字图片给网关
  async clientXbmToPublish(mac, obj) {
    let TOPIC_GW;
    if (mac) {
      TOPIC_GW = `${this.TOPIC_GW}/${mac}`
    } else {
      TOPIC_GW = this.TOPIC_GW
    }
    this.client = mqtt.connect(this.mqttConfig.suzhou.host, {
      username: this.mqttConfig.suzhou.username,
      password: this.mqttConfig.suzhou.password,
      clientId: this.mqttConfig.suzhou.clientId,
      keepalive: this.mqttConfig.suzhou.keepalive,
      reconnectPeriod: this.mqttConfig.suzhou.reconnectPeriod,
    });

    if (obj) {
      this.publish(TOPIC_GW, obj)
    }
    this.client.on('error', (err) => console.error('MQTT connection error:', err));
    this.client.on('close', () => console.log('MQTT connection closed'));
    this.client.on('offline', () => console.warn('MQTT client is offline'));
  }

  // 初始化 MQTT 客户端
  async init() {
    this.clientShanghai = mqtt.connect(this.mqttConfig.shanghai.host, {
      username: this.mqttConfig.shanghai.username,
      password: this.mqttConfig.shanghai.password,
      clientId: this.mqttConfig.shanghai.clientId,
      keepalive: this.mqttConfig.shanghai.keepalive,
      reconnectPeriod: this.mqttConfig.shanghai.reconnectPeriod,
    });
    this.clientShanghai.on('error', (err) => console.error('ShangHai MQTT connection error:', err));
    this.clientShanghai.on('close', () => console.log('ShangHai MQTT connection closed'));
    this.clientShanghai.on('offline', () => console.warn('ShangHai MQTT client is offline'));

    // 苏州连接
    this.client = mqtt.connect(this.mqttConfig.suzhou.host, {
      username: this.mqttConfig.suzhou.username,
      password: this.mqttConfig.suzhou.password,
      clientId: this.mqttConfig.suzhou.clientId,
      keepalive: this.mqttConfig.suzhou.keepalive,
      reconnectPeriod: this.mqttConfig.suzhou.reconnectPeriod,
    });

    this.client.on('error', (err) => console.error('MQTT connection error:', err));
    this.client.on('close', () => console.log('MQTT connection closed'));
    this.client.on('offline', () => console.warn('MQTT client is offline'));
  }

  // 发布消息
  async publish(topic: string, message) {
    // if (!this.client.connected) {
    //   console.warn('MQTT client not connected, message not sent.');
    //   return;
    // }

    this.client.publish(topic, JSON.stringify(message), { qos: 1 }, (err) => {
      if (err) {
        console.error(`Failed to publish message to ${topic}:`, err);
      } else {
        console.log(`Message published to ${topic}`);
      }
    });
  }


  // 关闭 MQTT 连接
  async close() {
    if (this.client) {
      this.client.end(false, () => console.log('MQTT client disconnected.'));
    }

    if (this.clientShanghai) {
      this.clientShanghai.end(false, () => console.log('MQTT client disconnected.'))
    }
  }
}